package com.yingpai.fitness.dvp_2_0.main.activity.shop;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bumptech.glide.Glide;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.timmy.tdialog.TDialog;
import com.timmy.tdialog.base.BindViewHolder;
import com.timmy.tdialog.listener.OnViewClickListener;
import com.yingpai.fitness.R;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.entity.shop.detail.PhotoEventMessage;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;

/**
 * Created by ASUS on 2018/10/17.
 */

public class PhotoActivity extends CommonActivity {

    private ViewPager viewPager;
    private LayoutInflater mInflater;
    private List<View> list;
    private TDialog tDialog;
    private PhotoEventMessage message;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo);

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    protected void initView() {
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        mInflater = LayoutInflater.from(this);
        list = new ArrayList<>();
        viewPager.setAdapter(pagerAdapter);

        EventBus.getDefault().register(this);
    }

    @Override
    protected void initData() {

    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onMessage(final PhotoEventMessage photoEventMessage) {
        message = photoEventMessage;
        list.clear();
        for (int i = 0; i < photoEventMessage.getList().size(); i++) {
            View v = mInflater.inflate(R.layout.photo_viewpager, null);
            PhotoView photo = v.findViewById(R.id.photo);
            photo.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
                @Override
                public void onPhotoTap(View view, float x, float y) {
                    finish();
                }

                @Override
                public void onOutsidePhotoTap() {

                }
            });

            photo.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    showSaveDialog(photoEventMessage.getPosition());
                    return false;
                }
            });
            Glide.with(getApplicationContext())
                    .load(photoEventMessage.getList().get(i))
                    .error(R.mipmap.default_small_bg)
                    .into(photo);
            list.add(v);
        }
        pagerAdapter.notifyDataSetChanged();
        viewPager.setCurrentItem(photoEventMessage.getPosition());
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(final int position) {
                PhotoView photoView = list.get(position).findViewById(R.id.photo);
                photoView.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
                    @Override
                    public void onPhotoTap(View view, float x, float y) {
                        finish();
                    }

                    @Override
                    public void onOutsidePhotoTap() {

                    }
                });

                photoView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        showSaveDialog(position);
                        return true;
                    }
                });
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    PagerAdapter pagerAdapter = new PagerAdapter() {
        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(list.get(position));
        }

        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(list.get(position));
            return list.get(position);
        }
    };


    private void showSaveDialog(final int position) {
        tDialog = new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.save_photo)
                .setScreenWidthAspect(this, 1.0f)
                .setGravity(Gravity.BOTTOM)
                .addOnClickListener(R.id.tv_open_camera, R.id.tv_cancel)
                .setOnViewClickListener(new OnViewClickListener() {
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
                        switch (view.getId()) {
                            case R.id.tv_open_camera:
                                tDialog.dismiss();
                                OkGo.<File>post(message.getList().get(position))
                                        .tag(this)
                                        .execute(new FileCallback(Environment.getExternalStorageDirectory()
                                                + File.separator + Environment.DIRECTORY_DCIM
                                                + File.separator + "Camera" + File.separator, message.getList().get(position).substring(message.getList().get(position).lastIndexOf("/") + 1)) {
                                            @Override
                                            public void onSuccess(Response<File> response) {
                                                showToast("保存成功 路径为：" + response.body().getAbsolutePath());
                                                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(response.body().getAbsolutePath()))));
                                            }

                                            @Override
                                            public void downloadProgress(Progress progress) {
                                                super.downloadProgress(progress);
                                            }
                                        });
                                break;
                            case R.id.tv_cancel:
                                tDialog.dismiss();
                                break;
                        }
                    }
                })
                .create()
                .show();
    }

}
